/*
 * JavaScript file
 */
function init(){
    NOKIA_PATH_JAVASCRIPT = 'lib/';
    NOKIA_PATH_STYLE_ROOT = 'themes/nokia/base/';
    URL_PRODUCTLIST = 'http://www.izinin.fn-sandbox.net/mobile_getproductlist.php';
	AUTHDIGEST = '';
	window.buyButtonArr = [];

	// IAP API related literals below
	KUserAndDevice = "UserAndDeviceId";
	KProductData = "ProductData";
	KPurchaseProduct = "PurchaseProduct";
	// ~~~~
	KIAPCmd = "command";
	KProductID = "productId";
    
    //Necessary if you are working on 3rd Ed devices		
    if (window.widget) {
        widget.setNavigationEnabled(false);
    }
    
    Nokia.use('template-default', 'busy', 'customizablelist', 'button', 
		function(){
		
		//setup
        inapprogress = new Nokia.Busy({
            element: document.body,
            autoOpen: false
        });
  
        Nokia.dom.append(document.body, Nokia.dom.parseHTML('<div id="productlist"></div>'));
        productListCtrl = new Nokia.CustomizableList({element: '#productlist'});

        // utility functions
        function appendProduct(product, index, array){
            var item_placeholder = Nokia.dom.parseHTML(
							'<div id="product_' + index + '" class="ui-helper-clearfix">' +
									'<span id="buy_' + index + '" ></span>' + 
										'<span id="productinfo_' + index + '" > Please wait product <' + 
											product + '> data is loading...</span></div>');
            productListCtrl.addItem(item_placeholder);

			window.buyButtonArr[index] = new Nokia.Button({
				element: '#buy_' + index,
				disabled: true,
				label: 'Wait...',
				click: function(){
					APIBridge.Internal._sendRequest( 
						"/nokia/iapplugin?" + KIAPCmd + "=" + KPurchaseProduct + "&" + KProductID + "=" + product, 
						null,
						function(req){
							alert("Purchasing result: <" + req.responseText + ">");
						},
						null);	
				}
			});

			APIBridge.Internal._sendRequest( 
				"/nokia/iapplugin?" + KIAPCmd + "=" + KProductData + "&" + KProductID + "=" + product, 
				null,
				function(req){
					var expr = '#productinfo_' + index;
					$(expr).html(req.responseText);
					$(expr).css("color", "darkgreen");
					var expr = '#buy_' + index;
					window.buyButtonArr[index].enable();
					window.buyButtonArr[index].setLabel("Buy");
				},
				null);	
        }

		//start execution 
        inapprogress.hide();
		APIBridge.Internal._sendRequest( 
			"/nokia/iapplugin?" + KIAPCmd + "=" + KUserAndDevice, 
			null,
			function(req){
				AUTHDIGEST = req.responseText;					
		        inapprogress.show();
		        window.jQuery.getJSON(URL_PRODUCTLIST + "?callback=?", null, function(productList, result, xdr){
		            productList.forEach(appendProduct);
		            productListCtrl.show();
		            inapprogress.hide();
		        });	
			},
			null);
    });
}
